import Vue from 'vue'
import VueRouter from 'vue-router'
import { adminRoutes } from './admin'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Layout from '@/views/layout/Layout.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/user/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/user/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/main',
    component: Layout,
    redirect: '/main/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/Home.vue'),
        meta: { title: '首页', requireAuth: true }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/user/Profile.vue'),
        meta: { title: '个人中心', requireAuth: true }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('@/views/user/ChangePassword.vue'),
        meta: { title: '修改密码', requireAuth: true }
      },
      // 宠物相关路由
      {
        path: 'pets',
        name: 'PetList',
        component: () => import('@/views/pet/PetList.vue'),
        meta: { title: '宠物列表' }
      },
      {
        path: 'pets/create',
        name: 'PetCreate',
        component: () => import('@/views/pet/PetForm.vue'),
        meta: { title: '添加宠物', requireAuth: true }
      },
      {
        path: 'pets/:id/edit',
        name: 'PetEdit',
        component: () => import('@/views/pet/PetForm.vue'),
        meta: { title: '编辑宠物', requireAuth: true }
      },
      {
        path: 'pets/:id',
        name: 'PetDetail',
        component: () => import('@/views/pet/PetDetail.vue'),
        meta: { title: '宠物详情' }
      },
      {
        path: 'my-pets',
        name: 'MyPets',
        component: () => import('@/views/pet/MyPets.vue'),
        meta: { title: '我的宠物', requireAuth: true }
      },
      // 论坛相关路由
      {
        path: 'forum',
        name: 'PostList',
        component: () => import('@/views/forum/PostList.vue'),
        meta: { title: '宠物论坛' }
      },
      {
        path: 'forum/create',
        name: 'PostCreate',
        component: () => import('@/views/forum/PostForm.vue'),
        meta: { title: '发布帖子', requireAuth: true }
      },
      {
        path: 'forum/:id/edit',
        name: 'PostEdit',
        component: () => import('@/views/forum/PostForm.vue'),
        meta: { title: '编辑帖子', requireAuth: true }
      },
      {
        path: 'forum/:id',
        name: 'PostDetail',
        component: () => import('@/views/forum/PostDetail.vue'),
        meta: { title: '帖子详情' }
      },
      // 服务相关路由
      {
        path: 'services',
        name: 'ServiceList',
        component: () => import('@/views/service/ServiceList.vue'),
        meta: { title: '服务列表' }
      },
      {
        path: 'services/create',
        name: 'ServiceCreate',
        component: () => import('@/views/service/ServiceForm.vue'),
        meta: { title: '添加服务', requireAuth: true, requireAdmin: true }
      },
      {
        path: 'services/:id/edit',
        name: 'ServiceEdit',
        component: () => import('@/views/service/ServiceForm.vue'),
        meta: { title: '编辑服务', requireAuth: true, requireAdmin: true }
      },
      {
        path: 'services/:id',
        name: 'ServiceDetail',
        component: () => import('@/views/service/ServiceDetail.vue'),
        meta: { title: '服务详情' }
      },
      // 预约相关路由
      {
        path: 'appointments',
        name: 'AppointmentList',
        component: () => import('@/views/appointment/AppointmentList.vue'),
        meta: { title: '预约管理', requireAuth: true, requireAdmin: true }
      },
      {
        path: 'appointments/:id',
        name: 'AppointmentDetail',
        component: () => import('@/views/appointment/AppointmentDetail.vue'),
        meta: { title: '预约详情', requireAuth: true }
      },
      {
        path: 'my-appointments',
        name: 'MyAppointments',
        component: () => import('@/views/appointment/MyAppointments.vue'),
        meta: { title: '我的预约', requireAuth: true }
      },
      // 商城相关路由
      {
        path: 'shop',
        name: 'Shop',
        component: () => import('@/views/shop/ProductList.vue'),
        meta: { title: '商城', requireAuth: true }
      },
      {
        path: 'shop/products/:id',
        name: 'ProductDetail',
        component: () => import('@/views/shop/ProductDetail.vue'),
        meta: { title: '商品详情', requireAuth: true }
      },
      {
        path: 'shop/cart',
        name: 'Cart',
        component: () => import('@/views/shop/Cart.vue'),
        meta: { title: '购物车', requireAuth: true }
      },
      {
        path: 'shop/checkout',
        name: 'Checkout',
        component: () => import('@/views/shop/Checkout.vue'),
        meta: { title: '结算', requireAuth: true }
      },
      {
        path: 'shop/payment/:orderId',
        name: 'Payment',
        component: () => import('@/views/shop/Payment.vue'),
        meta: { title: '支付', requireAuth: true }
      },
      {
        path: 'shop/orders',
        name: 'OrderList',
        component: () => import('@/views/shop/OrderList.vue'),
        meta: { title: '我的订单', requireAuth: true }
      },
      {
        path: 'shop/orders/:id',
        name: 'OrderDetail',
        component: () => import('@/views/shop/OrderDetail.vue'),
        meta: { title: '订单详情', requireAuth: true }
      }
    ]
  },
  adminRoutes // 添加管理系统路由
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决导航重复的错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err
    }
  })
}

// 白名单路由
const whiteList = ['/login', '/register']

// 导航守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 宠物服务平台` : '宠物服务平台'
  
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/main/home' })
    } else {
      const userInfo = store.state.user.userInfo
      if (!userInfo) {
        store.dispatch('user/getUserInfo').then(response => {
          const role = response.role
          if (to.path.startsWith('/admin') && role !== 'ADMIN') {
            next('/main/home')
          } else {
            next()
          }
        })
      } else {
        if (to.path.startsWith('/admin') && userInfo.role !== 'ADMIN') {
          next('/main/home')
        } else {
          next()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

// 判断是否有权限
function hasPermission(role, roles) {
  if (!roles) return true
  return roles.includes(role)
}

export default router 